package com.bxs.demo;

import java.io.*;
import java.net.ServerSocket;
import java.net.Socket;
import java.nio.charset.StandardCharsets;
import java.util.Scanner;

/**
 * 服务端客户端全双工通信测试
 */
public class SocketDemo {
    static class Server{
        ServerSocket serverSocket = null;
        public Server() throws IOException {
            serverSocket = new ServerSocket(9999);
        }

        public void start() throws IOException {
            //监听
            Socket socket = null;
            System.out.println("server start listening");
            while((socket = serverSocket.accept()) != null){
                System.out.println("accept...");
                InputStream inputStream = socket.getInputStream();
                OutputStream outputStream = socket.getOutputStream();
                BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream));
                StringBuffer sb = new StringBuffer();
                char buf[] = new char[1024];
                int len = 0;
                sb.append(bufferedReader.read(buf, 0, 1024));
                System.out.println("server receive: " + sb);
                BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(outputStream));
                bw.write("server response");
                bw.close();
                bufferedReader.close();
                outputStream.close();
                inputStream.close();
            }
        }
    }

    static class Client{
        public void send() throws IOException {
            System.out.println("send");
            Socket socket = new Socket("127.0.0.1", 9999);
            InputStream inputStream = socket.getInputStream();
            OutputStream outputStream = socket.getOutputStream();
            outputStream.write("client msg".getBytes(StandardCharsets.UTF_8));
            BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream));
            char buf[] = new char[1024];
            int len = 0;
            StringBuffer sb = new StringBuffer();
            do{
                len = bufferedReader.read(buf, 0, 1024);
                sb.append(buf, 0, len);
            }while (bufferedReader.ready());
            System.out.println("read: " + sb.toString());
        }
    }

    public static void main(String[] args) throws IOException {
        Server server = new Server();
        Thread t1 = new Thread(()-> {
            try {
                server.start();
            } catch (IOException e) {
                e.printStackTrace();
            }
        });

        Client client = new Client();
        Scanner scanner = new Scanner(System.in);
        String cmd;
        while(true){
            String next = scanner.next();
            System.out.println("input: " + next);
            client.send();
        }
    }


}
